package com.example.zhilierp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.zhilierp.entity.Permission;
import com.example.zhilierp.entity.RolePermission;
import com.example.zhilierp.mapper.PermissionMapper;
import com.example.zhilierp.mapper.RolePermissionMapper;
import com.example.zhilierp.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 权限服务实现类
 * 实现权限相关的业务逻辑
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public List<Permission> selectPermissionsByRoleId(Long roleId) {
        return permissionMapper.selectPermissionsByRoleId(roleId);
    }

    @Override
    public List<Permission> selectPermissionsByUserId(Long userId) {
        return permissionMapper.selectPermissionsByUserId(userId);
    }

    @Override
    public List<Permission> getPermissionTree() {
        // 查询所有权限
        LambdaQueryWrapper<Permission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Permission::getDeleted, 0)
                   .eq(Permission::getStatus, 1)
                   .orderByAsc(Permission::getSort);
        List<Permission> permissions = list(queryWrapper);
        
        // 构建权限树
        return buildPermissionTree(permissions, 0L);
    }

    @Override
    public List<Permission> getUserMenuTree(Long userId) {
        // 查询用户的所有权限
        List<Permission> permissions = permissionMapper.selectPermissionsByUserId(userId);
        
        // 过滤出菜单类型的权限（type=0目录，type=1菜单）
        List<Permission> menuPermissions = permissions.stream()
                .filter(p -> p.getType() == 0 || p.getType() == 1)
                .collect(Collectors.toList());
        
        // 构建菜单树
        return buildPermissionTree(menuPermissions, 0L);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveRolePermissions(Long roleId, List<Long> permissionIds) {
        // 先删除角色已有的权限关联
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RolePermission::getRoleId, roleId);
        rolePermissionMapper.delete(queryWrapper);
        
        // 如果权限ID列表不为空，则添加新的权限关联
        if (permissionIds != null && !permissionIds.isEmpty()) {
            for (Long permissionId : permissionIds) {
                RolePermission rolePermission = new RolePermission();
                rolePermission.setRoleId(roleId);
                rolePermission.setPermissionId(permissionId);
                rolePermissionMapper.insert(rolePermission);
            }
            return true;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRolePermissionsByRoleIds(Long[] roleIds) {
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(RolePermission::getRoleId, Arrays.asList(roleIds));
        return rolePermissionMapper.delete(queryWrapper) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteRolePermissionsByPermissionIds(Long[] permissionIds) {
        LambdaQueryWrapper<RolePermission> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(RolePermission::getPermissionId, Arrays.asList(permissionIds));
        return rolePermissionMapper.delete(queryWrapper) > 0;
    }

    /**
     * 构建权限树
     * @param permissions 权限列表
     * @param parentId 父权限ID
     * @return 权限树
     */
    private List<Permission> buildPermissionTree(List<Permission> permissions, Long parentId) {
        List<Permission> tree = new ArrayList<>();
        
        // 找到所有父权限ID等于parentId的权限
        List<Permission> parentPermissions = permissions.stream()
                .filter(p -> Objects.equals(p.getParentId(), parentId))
                .collect(Collectors.toList());
        
        // 对每个父权限，递归查找其子权限
        for (Permission permission : parentPermissions) {
            // 递归查找子权限
            List<Permission> children = buildPermissionTree(permissions, permission.getId());
            // 设置子权限
            // 注意：这里需要扩展Permission类，添加children字段
            // 由于当前Permission类没有children字段，这里只是构建了树结构，实际使用时需要处理
            tree.add(permission);
        }
        
        return tree;
    }
}